package com.ruoyi.buss.customer.controller;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.buss.customer.domain.ReportywxxLsb;
import com.ruoyi.buss.grid.cj.domain.DataCustomerInfoVO;
import com.ruoyi.buss.grid.cj.domain.DataWgWgcj;
import com.ruoyi.buss.grid.sh.domain.DataGtgsh;
import com.ruoyi.buss.grid.sq.domain.DataWgWgsq;
import com.ruoyi.buss.utils.ListUtil;
import com.ruoyi.common.core.enums.ErrorCode;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.buss.customer.domain.DataCustomerInfo;
import com.ruoyi.buss.customer.service.IDataCustomerInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 客户信息Controller
 *
 * @author ruoyi
 * @date 2021-07-16
 */
@Api(tags = {"存量用户controller"})
@RestController
@RequestMapping("/customer")
public class DataCustomerInfoController extends BaseController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private IDataCustomerInfoService dataCustomerInfoService;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询客户信息列表
     */
    @ApiOperation(value = "查询存量客户列表", notes = "注意问题点")
    @PreAuthorize(hasPermi = "buss:customer:list")
    @GetMapping("/queryCustomerList")
    public TableDataInfo list(DataCustomerInfo dataCustomerInfo) {
        LoginUser userInfo = tokenService.getLoginUser();
        Integer ifStock = dataCustomerInfoService.ifStock(dataCustomerInfo);
        dataCustomerInfo.setIfStock(String.valueOf(ifStock));
        startPage("CUSTOMER_LEVEL_ZH DESC");
        List<DataCustomerInfo> list = dataCustomerInfoService.selectDataCustomerInfoList(dataCustomerInfo, userInfo);
        return getDataTable(list);
    }

    /**
     * 获取客户信息详细信息
     */
    @ApiOperation(value = "客户视图", notes = "统一入口")
    @PreAuthorize(hasPermi = "buss:customer:query")
    @GetMapping(value = "queryCustomerInfo/{idCard}")
    public AjaxResult getInfo(@PathVariable("idCard") String idCard) {
        if (StringUtils.isEmpty(idCard)) {
            return AjaxResult.error(ErrorCode.IllegalArument);
        }
        return AjaxResult.success(dataCustomerInfoService.selectDataCustomerInfoById(idCard));
    }

    /**
     * 新增客户信息
     */
    @ApiOperation(value = "新增客户信息", notes = "统一新增入口")
    @PreAuthorize(hasPermi = "buss:customer:add")
    @Log(title = "新增客户信息", businessType = BusinessType.INSERT)
    @PostMapping("/addCustomer")
    public AjaxResult add(@Validated @RequestBody DataCustomerInfo dataCustomerInfo) {
        /**
         * 村居客户所需条件不能为空
         */
        if (!ListUtil.isNullOrEmpty(dataCustomerInfo.getDataWgWgcj())) {
            DataWgWgcj dataWgWgcj = dataCustomerInfo.getDataWgWgcj().get(0);
            if (StringUtils.isEmpty(dataWgWgcj.getTown())) {
                throw new CustomException("所属镇不能为空");
            }
            if (StringUtils.isEmpty(dataWgWgcj.getVillage())) {
                throw new CustomException("所属村不能为空");
            }
        }

        /**
         * 社区客户所需条件不能为空
         */
        if (!ListUtil.isNullOrEmpty(dataCustomerInfo.getDataWgWgsq())) {
            DataWgWgsq dataWgWgsq = dataCustomerInfo.getDataWgWgsq().get(0);
            if (StringUtils.isEmpty(dataWgWgsq.getSssjsq())) {
                throw new CustomException("所属社区不能为空");
            }
            if (StringUtils.isEmpty(dataWgWgsq.getSssq())) {
                throw new CustomException("所属小区不能为空");
            }
        }

        /**
         * 个体工商户所需条件不能为空
         */
        if (!ListUtil.isNullOrEmpty(dataCustomerInfo.getDataGtgsh())) {
            DataGtgsh dataGtgsh = dataCustomerInfo.getDataGtgsh().get(0);
            if (StringUtils.isEmpty(dataGtgsh.getSssjsq())) {
                throw new CustomException("所属社区不能为空");
            }
            if (StringUtils.isEmpty(dataGtgsh.getSssq())) {
                throw new CustomException("所属小区不能为空");
            }
            if (StringUtils.isEmpty(dataGtgsh.getShmt())) {
                throw new CustomException("商户门头不能为空");
            }
            if (StringUtils.isEmpty(dataGtgsh.getSshy())) {
                throw new CustomException("所属行业不能为空");
            }
            if (StringUtils.isEmpty(dataGtgsh.getJyzk())) {
                throw new CustomException("经营状况不能为空");
            }
            if (StringUtils.isEmpty(dataGtgsh.getBusinessLicense())) {
                throw new CustomException("营业执照不能为空");
            }
            if (StringUtils.isEmpty(dataGtgsh.getHeadPhoto())) {
                throw new CustomException("门头照不能为空");
            }
            if (StringUtils.isEmpty(dataGtgsh.getLng()) || StringUtils.isEmpty(dataGtgsh.getLat())) {
                throw new CustomException("商户定位地址为空,请重新定位!!");
            }
        }

        LoginUser userInfo = tokenService.getLoginUser();
        return toAjax(dataCustomerInfoService.insertDataCustomerInfo(dataCustomerInfo, userInfo));
    }

    /**
     * 修改客户信息
     */
    @ApiOperation(value = "修改客户信息", notes = "统一修改入口 id为必传条件")
    @PreAuthorize(hasPermi = "buss:customer:edit")
    @Log(title = "修改客户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody DataCustomerInfo dataCustomerInfo) {
        if (StringUtils.isEmpty(dataCustomerInfo.getId())) {
            throw new CustomException("ID不能为空");
        }
        /**
         * 村居客户所需条件不能为空
         */
        if (!ListUtil.isNullOrEmpty(dataCustomerInfo.getDataWgWgcj())) {
            for (DataWgWgcj dataWgWgcj : dataCustomerInfo.getDataWgWgcj()) {

//				if (StringUtils.isEmpty(dataWgWgcj.getId())) {
//					throw new CustomException("村居ID不能为空");
//				}
                if (StringUtils.isEmpty(dataWgWgcj.getTown())) {
                    throw new CustomException("所属镇不能为空");
                }
                if (StringUtils.isEmpty(dataWgWgcj.getVillage())) {
                    throw new CustomException("所属村不能为空");
                }
            }
        }

        /**
         * 社区客户所需条件不能为空
         */
        if (!ListUtil.isNullOrEmpty(dataCustomerInfo.getDataWgWgsq())) {

            for (DataWgWgsq dataWgWgsq : dataCustomerInfo.getDataWgWgsq()) {
//            DataWgWgsq dataWgWgsq =  dataCustomerInfo.getDataWgWgsq().get(0);
//				if (StringUtils.isEmpty(dataWgWgsq.getId())) {
//					throw new CustomException("社区ID不能为空");
//				}
                if (StringUtils.isEmpty(dataWgWgsq.getSssjsq())) {
                    throw new CustomException("社区所属社区不能为空");
                }
                if (StringUtils.isEmpty(dataWgWgsq.getSssq())) {
                    throw new CustomException("社区所属小区不能为空");
                }
            }
        }

        /**
         * 个体工商户所需条件不能为空
         */
        if (!ListUtil.isNullOrEmpty(dataCustomerInfo.getDataGtgsh())) {
            for (DataGtgsh dataGtgsh : dataCustomerInfo.getDataGtgsh()) {
                /**经营状况 为关闭时，不校验其它参数*/
                if (StringUtils.isEmpty(dataGtgsh.getJyzk())) {
                    throw new CustomException("商户经营状况不能为空");
                } else if (!"0".equals(dataGtgsh.getJyzk())) {
                    if (StringUtils.isEmpty(dataGtgsh.getSssjsq())) {
                        throw new CustomException("商户所属社区不能为空");
                    }
                    if (StringUtils.isEmpty(dataGtgsh.getSssq())) {
                        throw new CustomException("商户所属小区不能为空");
                    }
                    if (StringUtils.isEmpty(dataGtgsh.getShmt())) {
                        throw new CustomException("商户门头不能为空");
                    }
                }


            }
        }
        LoginUser userInfo = tokenService.getLoginUser();
        return toAjax(dataCustomerInfoService.updateDataCustomerInfo(dataCustomerInfo, userInfo));
    }

    /**
     * 查询客户信息列表
     */
    @ApiOperation(value = "客户星级变更记录")
    @PreAuthorize(hasPermi = "buss:customer:KhLevelChange")
    @GetMapping("/KhLevelChange")
    public TableDataInfo KhLevelChange(DataCustomerInfoVO dataCustomerInfo) {
        LoginUser userInfo = tokenService.getLoginUser();
        startPage();
        List<Map<String, Object>> list = dataCustomerInfoService.KhLevelChange(dataCustomerInfo, userInfo);
        return getDataTable(list);
    }

    @ApiOperation(value = "业务信息分析")
    @PreAuthorize(hasPermi = "buss:customer:ywxxtjt")
    @GetMapping("/ywxxtjt")
    public TableDataInfo ywxxtjt(ReportywxxLsb ReportywxxLsb) {
        LoginUser userInfo = tokenService.getLoginUser();
        List<ReportywxxLsb> list = dataCustomerInfoService.ywxxtjt(ReportywxxLsb);
        return getDataTable(list);
    }


    /**
     * 删除客户信息
     */
    @ApiOperation(value = "删除客户信息-停用", notes = "暂时停用")
    @PreAuthorize(hasPermi = "buss:customer:remove")
    @Log(title = "删除客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
//        return toAjax(dataCustomerInfoService.deleteDataCustomerInfoByIds(ids));
        return null;
    }

    /**
     * 导出客户信息列表
     */
    @ApiOperation(value = "导出客户信息-停用", notes = "暂时停用")
    @PreAuthorize(hasPermi = "buss:customer:export")
    @Log(title = "导出客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DataCustomerInfo dataCustomerInfo) throws IOException {
        LoginUser userInfo = tokenService.getLoginUser();

        List<DataCustomerInfo> list = dataCustomerInfoService.selectDataCustomerInfoList(dataCustomerInfo, userInfo);
        ExcelUtil<DataCustomerInfo> util = new ExcelUtil<DataCustomerInfo>(DataCustomerInfo.class);
        util.exportExcel(response, list, "客户信息数据");
    }

    /**
     * 通过机构号，查询该机构下属客户经理和柜员
     */
    @ApiOperation(value = "通过机构查询客户经理", notes = "机构ID不能为空")
    @PreAuthorize(hasPermi = "buss:customer:queryManager")
    @GetMapping("/queryManager")
    public TableDataInfo queryManager(DataCustomerInfo dataCustomerInfo) throws IOException {
        if (StringUtils.isEmpty(dataCustomerInfo.getOrgId())) {
            throw new CustomException("机构不能为空");
        }
        LoginUser userInfo = tokenService.getLoginUser();

        TableDataInfo tableDataInfo = remoteUserService.list(dataCustomerInfo.getOrgId());
        return tableDataInfo;
    }

    /**
     * 查询客户群体信息
     */
    @ApiOperation(value = "查询客户群体信息", notes = "机构ID不能为空")
    @PreAuthorize(hasPermi = "buss:customer:listGroup")
    @GetMapping("/listGroup")
    public TableDataInfo listGroup(DataCustomerInfo dataCustomerInfo) throws IOException {
        if (StringUtils.isEmpty(dataCustomerInfo.getOrgId())) {
            throw new CustomException("机构不能为空");
        }
        LoginUser userInfo = tokenService.getLoginUser();

        TableDataInfo tableDataInfo = remoteUserService.list(dataCustomerInfo.getOrgId());
        return tableDataInfo;
    }

    /**
     * 查询经纬度不为空的客户信息
     *
     * @return
     */
    @ApiOperation(value = "查询经纬度不为空的客户信息", notes = "查询经纬度不为空的客户信息")
    @GetMapping("/findCustomerInfo")
    public List<DataCustomerInfo> findCustomerInfoList() {
        LoginUser userInfo = tokenService.getLoginUser();
        List<DataCustomerInfo> customerInfoList = dataCustomerInfoService.findCustomerInfoList(userInfo);
        return customerInfoList;
    }

    /**
     * 更新客户的经纬度
     */
    @ApiOperation(value = "客户经纬度更新", notes = "统一入口")
    @GetMapping(value = "updateCustomerLatLng/{idCard}/{lat}/{lng}")
    public AjaxResult updateCustomerLatLng(@PathVariable("idCard") String idCard, @PathVariable("lat") String lat, @PathVariable("lng") String lng) {
        if (StringUtils.isEmpty(idCard) || StringUtils.isEmpty(lat) || StringUtils.isEmpty(lng)) {
            return AjaxResult.error(ErrorCode.IllegalArument);
        }
        dataCustomerInfoService.updateCustomerLatLng(idCard, lat, lng);
        return AjaxResult.success();
    }

    /**
     * 查询存量客户经纬度为空的客户信息
     */
    @ApiOperation(value = "查询存量客户经纬度为空", notes = "注意问题点")
    @GetMapping("/queryCustomerlatlng")
    public TableDataInfo queryCustomerlatlng(DataCustomerInfo dataCustomerInfo) {
        LoginUser userInfo = tokenService.getLoginUser();
        Integer ifStock = dataCustomerInfoService.ifStock(dataCustomerInfo);
        dataCustomerInfo.setIfStock(String.valueOf(ifStock));
        startPage("CUSTOMER_LEVEL_ZH DESC");
        List<DataCustomerInfo> list = dataCustomerInfoService.queryCustomerlatlngEmpty(userInfo);
        return getDataTable(list);
    }


}
